package com.xjggb.future;

import java.util.concurrent.*;

public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        show3();

    }


    /*
    * 配合多线程+线程池处理复杂业务
    * */
    public static void show3(){

        long l = System.currentTimeMillis();

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            TimeUnit.MICROSECONDS.sleep(500);
            return "来了";
        });
        executorService.execute(futureTask1);
        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            TimeUnit.MICROSECONDS.sleep(500);
            return "小老";
        });
        executorService.execute(futureTask2);

        FutureTask<String> futureTask3 = new FutureTask<>(() -> {
            TimeUnit.MICROSECONDS.sleep(500);
            return "弟";
        });
        executorService.execute(futureTask3);

        StringBuilder stringBuilder = new StringBuilder();
        try {
            stringBuilder.append(futureTask1.get());
            stringBuilder.append(futureTask2.get());
            stringBuilder.append(futureTask3.get());
            long l1 = System.currentTimeMillis();
            System.out.println("stringBuilder = " + stringBuilder.toString()+"--耗时--"+(l1-l));

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }


    }

    /*
    * 函数式编程
    * */
    public static void show2() throws ExecutionException, InterruptedException {
        FutureTask<String> stringFutureTask = new FutureTask<>(() -> {
            return "函数式编程";
        });

        Thread t2 = new Thread(stringFutureTask, "T2");
        t2.start();

        System.out.println("t2 = " + stringFutureTask.get());

    }

    public static void show1() throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(new MyThread());

        new Thread(futureTask,"t1"){

        }.start();
        System.out.println("futureTask.get() = " + futureTask.get()+"现成名称"+Thread.currentThread().getName());
    }

}

class  MyThread implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "hello";
    }
}